package View
{
	import laya.ui.Box;
	import laya.ui.Image;
	import laya.utils.Handler;
	
	import ui.GameUI;
	
	/**
	 * @author 刘吉
	 * @E-mail:liuji@mokylin.com
	 * 创建时间：2016-11-24 下午8:49:50
	 */
	
	public class GameView extends GameUI
	{
		private const MOLE_NUM:int = 9;
		private var moleVec:Vector.<Mole>;
		private var score:int = 0;
		private var hammer:Hammer;
		
		public function GameView()
		{
			super();
			
			moleVec = new Vector.<Mole>();
			init();
		}
		
		private function init():void
		{
			for (var i:int = 0; i < MOLE_NUM; i++) 
			{
				var box:Box = this.getChildByName("item" + i) as Box;
				var handler:Handler = new Handler(this, updateScore);
				var mole:Mole = new Mole(box.getChildByName("normal") as Image, 
					box.getChildByName("hit") as Image, 
					box.getChildByName("imgScore")as Image,
					24, 
					handler);
				moleVec.push(mole);
			}
			
			hammer = new Hammer();
			hammer.visible = false;
			this.addChild(hammer);
		}
		
		public function gameStart():void
		{
			score = 0;
			updateScore(1);
			hammer.visible = true;
			hammer.start();
			this.timeBar.value = 1;
			Laya.timer.loop(1000, this, onLoop);
		}
		
		private function onLoop():void
		{
			timeBar.value -= 1/90;
			if(timeBar.value <= 0)
			{
				gameOver();
				return;
			}
			var random:Number = Math.floor(Math.random() * MOLE_NUM);
			moleVec[random].show();
		}
		
		private function gameOver():void
		{
			Laya.timer.clear(this, onLoop);
			hammer.visible = false;
			hammer.end();
			
			if(!DaDiShu.gameOverView)
			{
				DaDiShu.gameOverView = new GameOverView();
			}
			DaDiShu.gameOverView.setScore(score);
			this.addChild(DaDiShu.gameOverView);
		}
		
		private function updateScore(type:Number):void
		{
			var tmp:int = type == 1 ? -100 : 100;
			score += tmp;
			if(score < 0)
			{
				score = 0;
			}
			
			var tmp1:int = score;
			trace("score:"+score);
			var data:Object = {};
			for (var i:int = 9; i >= 0; i--) 
			{
				data["item"+i] = {index:Math.floor(tmp1 % 10)};
				tmp1 /= 10;
			}
			this.boxScore.dataSource = data;
		}
	}
}